from django.db import models
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import User
from datetime import datetime, timedelta
from d115.fields import AutoSlugField
from d115.mixins import *

class Task(AuditMixin):
    title = models.CharField(max_length=512, verbose_name=_('Title'))
    content = models.TextField(verbose_name=_('Content'), blank=True, null=True)
    status = models.CharField(max_length=255, choices=(("pending", _("Pending")), ("active", _("Active")), ("completed", _("Completed"))), default="pending", verbose_name=_("Status"))
    assigned_to = models.ForeignKey(User, blank=True, null=True, verbose_name=_("Assigned to"), related_name="tasks")
    progress = models.PositiveIntegerField(blank=True, null=True, verbose_name=_("% Progress"))
    priority = models.CharField(max_length=20, choices=(("10", _("Critical")), ("20", _("High priority")), ("30", _("Normal")), ("40", _("Can wait"))), default="30", verbose_name=_("Priority"))
    duedate = models.DateTimeField(blank=True, null=True, verbose_name=_("Due date"))
    date_completed = models.DateTimeField(blank=True, null=True, editable=False, verbose_name=_("Date completed"))

    def __unicode__(self):
        return u"%s" % self.title

    class Meta(AuditMixin.Meta):
        verbose_name=_("project task")
        verbose_name_plural=_("project tasks")
        ordering = ["priority", "duedate", "-created"]

    def save(self, *args, **kwargs):
        if not self.date_completed and self.status=='completed':
            self.date_completed = datetime.now()
        super(Task, self).save(*args, **kwargs)

    def comment_count(self):
        return self.comments.count()
    comment_count.short_description = "Comments"

class TaskComment(AuditMixin):
    task = models.ForeignKey(Task, related_name="comments", editable=False)
    comment = models.TextField(verbose_name=_("Comment"), blank=True, null=True)

    class Meta(AuditMixin.Meta):
        verbose_name=_("task comment")
        verbose_name_plural=_("task comments")

    def __unicode__(self):
        return u"%s" % self.created_by
